package com.ybox.gateway.service.impl;

import com.ybox.common.core.constant.CacheConstants;
import com.ybox.common.core.constant.Constants;
import com.ybox.common.core.exception.CaptchaException;
import com.ybox.common.core.utils.StringUtils;
import com.ybox.common.core.utils.uuid.IdUtils;
import com.ybox.common.core.web.domain.AjaxResult;
import com.ybox.common.redis.service.RedisService;
import com.ybox.gateway.captcha.*;
import com.ybox.gateway.captcha.base.Captcha;
import com.ybox.gateway.captcha.utils.CaptchaUtil;
import com.ybox.gateway.config.properties.CaptchaProperties;
import com.ybox.gateway.service.ValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.IOException;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 验证码实现处理
 *
 * @author ych
 */
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private CaptchaProperties captchaProperties;

    /**
     * 生成验证码
     */
    @Override
    public AjaxResult createCaptcha() throws IOException, CaptchaException {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = captchaProperties.getEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        Captcha captcha = null;

        String captchaType = captchaProperties.getCodeType();
        String captchaImageType = captchaProperties.getImageType();
        Integer fontType = captchaProperties.getFontTypeToInt();
        Integer charType = captchaProperties.getCharTypeToInt();

        // 生成验证码
        // 如果指定了图片类型
        if (StringUtils.isNotEmpty(captchaType) && StringUtils.isNotEmpty(captchaImageType)) {
            captcha = CaptchaUtil.getCaptcha(captchaType, captchaImageType, captchaProperties.getWidth(), captchaProperties.getHeight(), captchaProperties.getLength());
        } else if (StringUtils.isEmpty(captchaType) && StringUtils.isNotEmpty(captchaImageType)) {
            // 未指定图片类型  随机生成
            captcha = CaptchaUtil.getCaptchaByRandomImageType(captchaType,captchaProperties.getWidth(), captchaProperties.getHeight(), captchaProperties.getLength());
        } else if (StringUtils.isNotEmpty(captchaType) && StringUtils.isEmpty(captchaImageType)) {
            // 未指定验证码类型 随机生成
            captcha = CaptchaUtil.getCaptchaByRandomCodeType(captchaImageType,captchaProperties.getWidth(), captchaProperties.getHeight(), captchaProperties.getLength());
        } else if (StringUtils.isEmpty(captchaType) && StringUtils.isEmpty(captchaImageType)) {
            // 未指定验证码类型 未指定图片类型 随机生成
            captcha = CaptchaUtil.getCaptchaByRandomImageTypeAndCodeType(captchaProperties.getWidth(), captchaProperties.getHeight(), captchaProperties.getLength());
        }

        try {
            if (Constants.IS_RANDOM.equals(fontType)) {
                if (!(captcha instanceof ChineseCaptcha || captcha instanceof ChineseGifCaptcha || captcha instanceof  ArithmeticCaptcha)) {
                    // 如果是中文或者算数，用默认字体就行否则报错，非中文或者算数则随机
                    captcha.setFont(new Random().nextInt(10));
                }
            } else {
                // 设置内置字体
                captcha.setFont(fontType);
                // 设置系统字体
                // captcha.setFont(new Font("楷体", Font.PLAIN, 28));
            }
        } catch (FontFormatException e) {
            e.printStackTrace();
            throw new CaptchaException("设置字体错误");
        }

        // 设置字符类型只能在captcha是SpecCaptcha和GifCaptcha子类才能设置,否则乱码
        if (captcha instanceof SpecCaptcha || captcha instanceof GifCaptcha) {
            if (!Constants.IS_RANDOM.equals(charType)) {
                // randNumber 将被赋值为一个 MIN 和 MAX 范围内的随机数
                // int randNumber =rand.nextInt(MAX - MIN + 1) + MIN;
                int randNumber = new Random().nextInt(6 - 1 + 1) + 1;
                captcha.setCharType(randNumber);
            } else {
                // 验证码字符类型
                captcha.setCharType(charType);
            }
        }

        redisService.setCacheObject(verifyKey, captcha.text(), Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        ajax.put("uuid", uuid);
        ajax.put("img", captcha.toBase64(""));
        return ajax;
    }

    /**
     * 校验验证码
     */
    @Override
    public void checkCaptcha(String code, String uuid) throws CaptchaException {
        if (StringUtils.isEmpty(code)) {
            throw new CaptchaException("验证码不能为空");
        }
        if (StringUtils.isEmpty(uuid)) {
            throw new CaptchaException("验证码已失效");
        }
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisService.getCacheObject(verifyKey);
        redisService.deleteObject(verifyKey);

        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException("验证码错误");
        }
    }

    @Override
    public void checkSms(String code, String uuid) throws CaptchaException {
        if (StringUtils.isEmpty(code)) {
            throw new CaptchaException("验证码不能为空");
        }
        if (StringUtils.isEmpty(uuid)) {
            throw new CaptchaException("验证码已失效");
        }
        String verifyKey = CacheConstants.SMS_CODE_KEY + uuid;
        Map<String,String> sms = redisService.getCacheObject(verifyKey);
        String smsCode = sms.get("code");
        redisService.deleteObject(verifyKey);
        if (!code.equalsIgnoreCase(smsCode)) {
            throw new CaptchaException("验证码错误");
        }
    }
}
